package com.symbio.ishenapi.background.model;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.symbio.ishenapi.background.model.base.BaseTmGroupMembers;
import com.symbio.ishenapi.background.vo.GroupMembersVO;
import com.symbio.ishenapi.background.vo.MembersVO;
import com.symbio.ishenapi.common.bean.QueryModel;
import io.jboot.db.annotation.Table;

import java.math.BigInteger;
import java.util.*;

/**
 * Generated by Jboot.
 */
@Table(tableName = "tm_group_members", primaryKey = "id")
public class TmGroupMembers extends BaseTmGroupMembers<TmGroupMembers> {

    public static TmGroupMembers dao = new TmGroupMembers();

    /**
     * 逻辑删除组成员信息
     * @param id
     */
    public void deleteMembers(int id) {
        String sql = "UPDATE tm_group_members SET status = 0 WHERE id = "+id;
        Db.update(sql);
    }

    /**
     * 成员列表查询
     * @param queryModel  分页参数
     * @param roleCode    0.组长1.成员
     * @param groupId     组ID
     * @return
     */
    public Map findListByParam(QueryModel queryModel, String roleCode, String groupId,String userType) {
        Map<String,Object> map = new HashMap<>();
        String sqlCount = "SELECT count(tgm.id) FROM tm_group_members tgm LEFT JOIN tm_doctor_user tdu ON tgm.userId = tdu.id WHERE tgm.status = 1";
        String sql = "SELECT tgm.*,tdu.userHeadPortrait,tdu.userName FROM tm_group_members tgm LEFT JOIN tm_doctor_user tdu ON tgm.userId = tdu.id WHERE tgm.status = 1";

        if(!StrKit.isBlank(roleCode)){
            sqlCount += " and tgm.memberRoleCode = "+roleCode+"";
            sql += " and tgm.memberRoleCode = "+roleCode+"";
        }
        if(!StrKit.isBlank(groupId)){
            sqlCount += " and tgm.groupId = "+groupId+"";
            sql += " and tgm.groupId = "+groupId+"";
        }
        if(!StrKit.isBlank(userType)){
            if(userType.equals("0")){
                userType = "医生";
            }else {
                userType = "患者";
            }
            sqlCount += " and tgm.userType = '"+userType+"'";
            sql += " and tgm.userType = '"+userType+"'";
        }
        int count = Db.queryInt(sqlCount);
        sql += " ORDER BY tgm.createTime LIMIT "+queryModel.getPage()+","+queryModel.getLimit()+"";
        List<Record> data = Db.find(sql);
        map.put("count",count);
        map.put("data",data);
        return map;
    }

    /**
     * 组长添加
     * @param tmGroupMembers
     */
    public void saveGroupLeader(TmGroupMembers tmGroupMembers) {
//        //后期在字典维护，暂时 0.组长1.成员
//        tmGroupMembers.setMemberRoleCode("0");
//        tmGroupMembers.setUserType("医生");
//
//        //每个分组只需要有一个组长，所以在添加之前清空组内的组长信息
//        String sqlDeleteLeader = "UPDATE tm_group_members SET status = 0 WHERE groupId = "+tmGroupMembers.getGroupId()+" and memberRoleCode = "+tmGroupMembers.getMemberRoleCode()+"";
//        Db.update(sqlDeleteLeader);
//
//        //更新分组信息内的组长信息
//        TmGroupInfo tmGroupInfo = TmGroupInfo.dao.findById(tmGroupMembers.getGroupId());
//        tmGroupInfo.setGroupLeaderId(tmGroupMembers.getUserId().intValue());
//        tmGroupInfo.setGroupLeaderName(tmGroupMembers.getUserName());
//        tmGroupInfo.update();
//
//        //更新成员表内组长信息
//        tmGroupMembers.setStatus("1");
//        tmGroupMembers.setCreateTime(new Date());
//        tmGroupMembers.save();
    }


    /**
     * 成员批量添加
     * @param tmGroupMembers
     */
    public void saveMembersList(GroupMembersVO tmGroupMembers) {
        List<TmGroupMembers> list = tmGroupMembers.getMemberList();
        if(list.size() >0){
            for(int i=0;i<list.size();i++){
                TmGroupMembers user = list.get(i);

                //后期字典维护
                user.setMemberRoleCode("1");
                if(user.getUserType().equals("0")){
                    user.setUserType("医生");
                }else {
                    user.setUserType("患者");
                }

                //判断数据库表内是否存在成员信息
                String sqlQueryUser = "SELECT * from tm_group_members WHERE status = 1 and groupId = "+user.getGroupId()+" and userId = "+user.getUserId()+"";
                TmGroupMembers queryUser = TmGroupMembers.dao.findFirst(sqlQueryUser);
                //不存在的时候新增成员信息
                if(queryUser == null){
                    user.setStatus("1");
                    user.setCreateTime(new Date());
                    user.save();
                }
            }
        }
    }

    /**
     * 成员列表删除
     * @param id
     */
    public void deleteMember(int id) {
        String sql = "update tm_group_members SET status = 0 WHERE id = "+id;
        Db.update(sql);
    }

    /**
     * 组成员添加
     * @param groupMembersVO
     */
    public void saveGroupMembers(GroupMembersVO groupMembersVO) {
        List<TmDepartmentMembers> list = groupMembersVO.getMembers();
        if(list.size() >0){
            for(int i=0;i<list.size();i++){
                TmDepartmentMembers department = list.get(i);
                //判断数据库表内是否存在成员信息
                String sqlQueryUser = "SELECT * from tm_group_members WHERE status = 1 and groupId = "+groupMembersVO.getGroupId()+" and userId = "+department.getDoctorId()+"";
                TmGroupMembers queryUser = TmGroupMembers.dao.findFirst(sqlQueryUser);
                if(queryUser == null){
                    queryUser = new TmGroupMembers();
                    queryUser.setGroupId(groupMembersVO.getGroupId());
                    queryUser.setUserId(department.getDoctorId());
                    queryUser.setUserName(department.getDoctorName());
                    queryUser.setMemberRoleCode("1");
                    if(groupMembersVO.getUserType().equals("0")){
                        queryUser.setUserType("医生");
                    }else {
                        queryUser.setUserType("患者");
                    }
                    queryUser.setStatus("1");
                    queryUser.setCreateTime(new Date());
                    //登录人信息  queryUser.setUserReferees();
                    queryUser.save();
                }
            }
        }
   }

    /**
     * 医生端科室分组获取患者列表
     * @param groupId
     * @param userType
     * @param doctorId
     * @return
     */
    public List<Record> findPatientMembers(String groupId, String userType, String doctorId) {
        String sql = "SELECT\n" +
                "\ttg.id,\n" +
                "\ttg.userId,\n" +
                "\ttp.userName,\n" +
                "\ttp.userSex,\n" +
                "\ttp.userAge,\n" +
                "\ttp.userHeadPortrait,\n" +
                "\ttp.userDoctorId,\n" +
                "\ttd.userName as doctorName\n" +
                "FROM\n" +
                "\ttm_group_members tg LEFT JOIN  \n" +
                "\ttm_patient_user tp ON tg.userId = tp.id\n" +
                "LEFT JOIN tm_doctor_user td ON tp.userDoctorId = td.id\n" +
                "WHERE tg.status = 1 and tg.groupId = "+groupId+" and tg.userType = '"+userType+"' ";
        if(!StrKit.isBlank(doctorId)){
            sql += " and userId in(SELECT userId from tm_patient_doctor tpu WHERE status = 1 and tpu.doctorId = "+doctorId+")";
        }
        return Db.find(sql);
    }

    public void deleteMembersByGroupId(String groupId, String userIds) {
        if(StrKit.isBlank(userIds)){userIds = "''";}
        String sql = "UPDATE tm_group_members SET status = 0 WHERE groupId = "+groupId+" and userId in ("+userIds+")";
        Db.update(sql);
    }

    /**
     * 获取成员所在的组ids
     * @param userId
     * @return
     */
    public List<Integer> findMemberGroupIds(String userId) {
        String sql = "SELECT groupId from tm_group_members WHERE status = 1 and userId = "+userId+"";
        return Db.query(sql);
    }

    /**
     * 医生端成员添加
     * @param membersVO
     */
    public void saveMemberListToDoctor(MembersVO membersVO) {
        //后期字典维护
        membersVO.setMemberRoleCode("1");
        if(membersVO.getUserType().equals("0")){
            membersVO.setUserType("医生");
        }else {
            membersVO.setUserType("患者");
        }
        membersVO.setStatus("1");
        if(!StrKit.isBlank(membersVO.getUserIds())){
            String[] ids = membersVO.getUserIds().split(",");
            for(int i=0;i<ids.length;i++){
                //判断数据库表内是否存在成员信息
                String sqlQueryUser = "SELECT * from tm_group_members WHERE status = 1 and groupId = "+membersVO.getGroupId()+" and userId = "+ids[i]+"";
                TmGroupMembers queryUser = TmGroupMembers.dao.findFirst(sqlQueryUser);
                //不存在的时候新增成员信息
                if(queryUser == null){
                    membersVO.setId(null);
                    membersVO.setCreateTime(new Date());
                    membersVO.setUserId(new BigInteger(ids[i]));
                    membersVO.save();
                }
            }
        }
    }

    /**
     * 医生端科室成员分组创建
     * @param groupMembersVO
     */
//    public void saveGroupMembers(GroupMembersVO groupMembersVO) {
//        List<TmDepartmentMembers> list = groupMembersVO.getMembers();
//        if(list.size() >0){
//            //首先保存组信息
//            TmGroupInfo tmGroupInfo = new TmGroupInfo();
//            tmGroupInfo.setGroupCode(UUID.randomUUID().toString());
//            tmGroupInfo.setGroupName(groupMembersVO.getGroupName());
//            tmGroupInfo.setDepartmentId(Integer.parseInt(groupMembersVO.getDepartmentId()));
//            tmGroupInfo.setGroupLeaderId(groupMembersVO.getGroupLeaderId());
//            tmGroupInfo.setGroupLeaderName(groupMembersVO.getGroupLeaderName());
//            //获取医生登录信息 待完善
//            tmGroupInfo.setCreateBy(groupMembersVO.getGroupLeaderName());
//            tmGroupInfo.setCreateTime(new Date());
//            tmGroupInfo.setStatus("1");
//            tmGroupInfo.save();
//
//            TmGroupInfo queryGroupInfo = TmGroupInfo.dao.queryGroupInfoByName(tmGroupInfo);
//
//            for(int i=0;i<list.size();i++){
//                TmDepartmentMembers department = list.get(i);
//                //判断数据库表内是否存在成员信息
//                String sqlQueryUser = "SELECT * from tm_group_members WHERE status = 1 and groupId = "+queryGroupInfo.getId()+" and userId = "+department.getDoctorId()+"";
//                TmGroupMembers queryUser = TmGroupMembers.dao.findFirst(sqlQueryUser);
//                if(queryUser == null){
//                    queryUser = new TmGroupMembers();
//                    queryUser.setGroupId(new BigInteger(queryGroupInfo.getId().toString()));
//                    queryUser.setUserId(department.getDoctorId());
//                    queryUser.setUserName(department.getDoctorName());
//                    queryUser.setMemberRoleCode("1");
//                    if(groupMembersVO.getUserType().equals("0")){
//                        queryUser.setUserType("医生");
//                    }else {
//                        queryUser.setUserType("患者");
//                    }
//                    queryUser.setStatus("1");
//                    queryUser.setCreateTime(new Date());
//                    //登录人信息  queryUser.setUserReferees();
//                    queryUser.save();
//                }
//            }
//        }
//   }
}
